//
//  StatusList.swift
//  SinaWeibo
//
//  Created by apple on 15/11/17.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD
import SDWebImage

class StatusList: NSObject {

    class func loadData(since_id:Int, max_id:Int,finished : (array:[Statues]?) ->()) {
    
        
        let urlSring = "2/statuses/friends_timeline.json"
        
        guard let token = UserAccountViewModel().token else {
            
            SVProgressHUD.showErrorWithStatus("网络君正在睡觉")
            return
        }
        
        var  parameters = ["access_token":token]
    
    //如果 since_id 大于0 则返回最新的微博
      if since_id > 0 {
        
        parameters["since_id"] = "\(since_id)"
        
      }
     
    //增加上拉加载更多字段
        if max_id > 0 {
            
            //把重复的那条全掉
            parameters["max_id"] = "\(max_id - 1)"
            
        }
        NetWorkingTools.shareTools.requestJSONDict(.GET, urlString: urlSring, parameters: parameters) { (result, error) -> () in
            
            
            
            //实例化数组
            var list = [Statues]()
            if let array = result!["statuses"] as? [[String:AnyObject]] {
                
                
                //遍历数组
                for item in array {
                    
                    //字典转模型
                    let s = Statues(dict: item)
                    
                    list.append(s)
                    
                }
                //完成回调
               // finished(array: list)
                StatusList.cacheStatusImage(list, finished: finished)
          }
            
      }
            
   }
    
    private class func cacheStatusImage(array:[Statues],finished : (array:[Statues]?) ->()) {
        
        //缓存单张图片
        if array.count == 0{
            
            finished(array: array)

            return
        }
        //创建群组
        let group = dispatch_group_create()
        
        for s in array {
            
            if let imageURLs = s.pictureURLs{
                
                if imageURLs.count != 1 {
                    
                    continue
                }
                
                //这里一定是单张图片
                for url in imageURLs{
                    
                    //进入组
                    dispatch_group_enter(group)
                   //开始下载图片
                    SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (_, _, _, _,_) -> Void in
                        
                        print("单张图片下载完成")
                        //出调度组
                        dispatch_group_leave(group)
                    })
                }
                
            }
        }
        
        //在主线程完成回调
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            
            print("所有的异步如片下载完成")
            //执行回调
            finished(array: array)
        }
    }
}

